<template>
  <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" :rules="rules">
        <div style="margin-top: -4px; margin-bottom:8px" >
    <el-radio-group v-model="radioVal" size="small" @change="radioChange">
      <el-radio-button label="全部履历"></el-radio-button>
      <el-radio-button label="故障(Down)" ></el-radio-button>
      <el-radio-button label="保养(PM)"></el-radio-button>
      <el-radio-button label="待机(IDLE)"></el-radio-button>
      <el-radio-button label="离线(OFF)"></el-radio-button>
    </el-radio-group>
  </div>
                      <el-form-item label="基准" prop="Type">
                          <el-radio-group v-model="queryParams.queryType" @change="radioChangeVal">
                            <el-radio label="EQP"> 父线 </el-radio>
                            <el-radio label="UNIT"> 子设备 </el-radio>
                          </el-radio-group>
                      </el-form-item>

                      <el-form-item label="日期" prop="dataTime" label-width="40px">
                        <WeekTimePicker type="datetime" v-model="queryParams.createTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px"/>
                        <span style="margin: 0px 6px;">~</span>
                        <WeekTimePicker type="datetime" v-model="queryParams.endTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px" />
                      </el-form-item>

                      <el-form-item label="制造区域" prop="factoryAreaId">
                            <el-select v-model="queryParams.factoryAreaId" placeholder="区域" clearable @change="areaChange" style="width: 70px">
                                <el-option
                                        v-for="dict in factoryAreaIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="制造类型" prop="productionTypeId">
                            <el-select v-model="queryParams.productionTypeId" placeholder="制造类型" clearable @change="productionTypeIdChange" style="width: 85px">
                                <el-option
                                        v-for="dict in listProductionTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="设备类型" prop="machineTypeId">
                            <el-select v-model="queryParams.machineTypeId" :disabled="isShow" placeholder="设备类型" clearable @change="machineTypeIdChange" style="width: 85px">
                                <el-option
                                        v-for="dict in listMachineTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="设备ID" prop="eqpId">
                              <!-- <el-select
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip v-model="queryParams.eqpId" placeholder="设备ID" @change="eqpTypeChange" style="width: 150px">
                                <el-option
                                        v-for="dict in listEqpTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select> -->

                            <el-select v-if="queryParams.queryType === 'EQP'" v-model="queryParams.eqpId" placeholder="设备ID" @change="eqpTypeChange" style="width: 150px">
                                <el-option
                                        v-for="dict in listEqpTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>

                            <el-select
                                v-if="queryParams.queryType === 'UNIT'"
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip v-model="queryParams.eqpId" placeholder="设备ID" @change="eqpTypeChange" style="width: 150px">
                                <el-option
                                        v-for="dict in listEqpTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @update:showSearch="showSearch ? height = 'calc(100% - 100px)' : height = 'calc(100% - 62px)'">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button
                      type="warning"
                      plain
                      icon="Download"
                      @click="handleExport"
                      v-hasPermi="['ASTManage:astHis:export']"
              >导出</el-button>
          </right-toolbar>
      </el-row>

      <t-ag-grid
          v-loading="loading"
          :style="{height}"
          :column-defs="column"
          :row-data="tableData"
          :row-buffer="20"
          row-selection="multiple"
          :suppress-row-click-selection="true"
          :row-multi-select-with-click="true"
          align="center"
          :defaultColDef = "{
              // suppressMenu:true
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          header-align="center"
          />
      <pagination
              v-show="total>0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
      />

  </div>
</template>

<script setup name="EpTimeHistory">

  import { listEptTimeHis } from "@/api/timeAnalysis/eptTimeHistory"
  import { factoryAreaIdOptions, listMachineTypeOptions } from '@/common/options'
  import { getMachineTypeId, getModelType, getEqpTypeId } from '@/common/affect'
  import moment from 'moment'
  import { allColumn, downColumn, pmColumn } from './config'
  import request from '@/utils/request'
  import { onMounted } from "vue"

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 1000,
      dataTime: null,
      createTime: moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00'),
      endTime: moment().format('YYYY-MM-DD 08:30:00'),
      factoryAreaId: '层前',
      productionTypeId: '叠瓦',
      machineTypeId: null,
      topMachineId: null,
      eqpId: null,
      queryType: 'EQP'
    },
    rules: {
      eqpId: [
        { required: true, message: "设备ID不能为空", trigger: "change" }
      ],
      factoryAreaId: [
        { required: true, message: "制造区域不能为空", trigger: "change" }
      ]

    }
  })

  const radioVal = ref('全部履历')
  const column = ref([])
  column.value = allColumn

  const isMultiple = ref(false)
  const { queryParams, rules } = toRefs(data)
  const showSearch = ref(true)
  const isShow = ref(true)
  const tableData = ref([])
  const total = ref(0)
  const loading = ref(false)
  const height = ref('calc(100% - 130px)')
  const listEqpTypeOptions = ref([])
  const { proxy } = getCurrentInstance()
  const listMachineTypeIdListOptions = ref([])

  const listProductionTypeOptions = ref([])

  const radioChange = (val) => {
    if(val === '全部履历') {
      column.value = allColumn
    } else if(val === '故障(Down)') {
      column.value = downColumn
    } else {
      column.value = pmColumn
    }
    handleQuery()
  }

  const radioChangeVal = (val) => {

    listEqpTypeOptions.value = []
    isShow.value = val === 'EQP' ? true : false
    isMultiple.value = val === 'UNIT' ? true : false
    queryParams.value.machineTypeId = ''
    queryParams.value.productionTypeId = ''
    queryParams.value.eqpId = ''
  }

  const areaChange = (target) => {
    queryParams.value.productionTypeId = null
    queryParams.value.machineTypeId = null
    queryParams.value.eqpId = null
    // listProductionTypeOptions.value = []
    if(!target.length) return
    getModelType({
      factoryAreaIdList: queryParams.value.factoryAreaId
    }).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  onMounted(() => {
    getModelType({
      factoryAreaIdList: '层前'
    }).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })

    productionTypeIdChange()
  })

  const getgetMachineTypeIdListInfo = (productionTypeId) => {
    return request({
      url: '/parameter/getMachineGroupByMachineTypeId/?machineType=' + productionTypeId,
      method: 'get'
    })
  }
  const productionTypeIdChange = (target) => {
    queryParams.value.machineTypeId = null
    queryParams.value.eqpId = null
    listMachineTypeOptions.value = []
    listEqpTypeOptions.value = []
    if(queryParams.value.queryType === 'UNIT') {
      getMachineTypeId({
        productionTypeIdList: queryParams.value.productionTypeId,
        isMainmachineType: 'N'
      }).then((res) => {
        res.rows.forEach(item => {
          listMachineTypeOptions.value.push({
            label: item,
            value: item
          })
        })
      })}

    if(queryParams.value.queryType === 'EQP'){
      getgetMachineTypeIdListInfo(
        queryParams.value.productionTypeId
      ).then((res) => {
        res.rows.forEach(item => {
          listEqpTypeOptions.value.push({
            label: item,
            value: item
          })
        })
      })}
  }

  const machineTypeIdChange = () => {
    listEqpTypeOptions.value = []
    queryParams.value.eqpType = null
    getEqpTypeId({
      machineType: queryParams.value.machineTypeId,
      isAnalysis: queryParams.value.radio === 'EQP' ? 'Y' : 'N'
    }).then((res) => {
      res.data.forEach(item => {
        listEqpTypeOptions.value.push({
          label: item.machineId,
          value: item.machineId
        })
      })
    })
  }

  const eqpTypeChange = (value) => {
    if(queryParams.value.radio === 'UNIT'){

      listUnitTypeOptions.value = []
      queryParams.value.unitType = null
      getUnitOptions({
        machineId: value
      }).then((res) => {
        res.rows.forEach((item) => {
          listUnitTypeOptions.value.push({
            label: item,
            value: item
          })
        })
      })
    }
  }

  const radioobj = {
    '全部履历': null,
    '故障(Down)': 'Down',
    '保养(PM)': 'PM',
    '待机(IDLE)': 'IDLE',
    '离线(OFF)': 'OFF'
  }

  function getList() {
    if(moment(queryParams.value.endTime).subtract(7, 'days')>moment(queryParams.value.createTime)){
      proxy.$modal.alertWarning('最多查询七天的数据')
      return
    }
    loading.value = true
    let _target = {
      fab: 'H05',
      startTime: moment(queryParams.value.createTime).format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment(queryParams.value.endTime).format('YYYY-MM-DD HH:mm:ss'),
      area: queryParams.value.factoryAreaId,
      process: queryParams.value.productionTypeId,
      machineTypeId: queryParams.value.machineTypeId,
      isMachineGroup: queryParams.value.queryType === 'EQP' ? 'Y' : 'N',
      model: 'Y',
      machineGroup: queryParams.value.queryType === 'EQP' ? queryParams.value.eqpId : null,
      machineId: queryParams.value.queryType === 'UNIT' ? queryParams.value.eqpId : null,
      eptStatus: radioobj[radioVal.value],
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize
    }

    listEptTimeHis(_target).then(response => {
      tableData.value = []
      response.rows.forEach((item) => {
        item.keepTime = Number(item.keepTime)
        tableData.value.push(item)
      })
      total.value = response.total
      loading.value = false
    })
  }

  function handleQuery() {
    proxy.$refs.queryRef.validate(valid => {
      if (valid) {
        queryParams.value.pageNum = 1
        getList()
      }
    })
  }

  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  const obj = {
    '全部履历': 'timeAnalysis/machineHistory/exportOeeBMachineWorkHistoryList',
    '故障(Down)': 'timeAnalysis/machineHistory/OeeBMachineWorkHistoryDownList',
    '保养(PM)': 'timeAnalysis/machineHistory/OeeBMachineWorkHistoryIdleList',
    '待机(IDLE)': 'timeAnalysis/machineHistory/OeeBMachineWorkHistoryIdleList',
    '离线(OFF)': 'timeAnalysis/machineHistory/OeeBMachineWorkHistoryIdleList'
  }

  function handleExport() {
    proxy.download(obj[radioVal.value], {
      fab: 'H05',
      startTime: moment(queryParams.value.createTime).format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment(queryParams.value.endTime).format('YYYY-MM-DD HH:mm:ss'),
      area: queryParams.value.factoryAreaId,
      process: queryParams.value.productionTypeId,
      machineTypeId: queryParams.value.machineTypeId,
      isMachineGroup: queryParams.value.queryType === 'EQP' ? 'Y' : 'N',
      model: 'Y',
      machineGroup: queryParams.value.queryType === 'EQP' ? queryParams.value.eqpId : null,
      machineId: queryParams.value.queryType === 'UNIT' ? queryParams.value.eqpId : null,
      eptStatus: radioobj[radioVal.value]
    }, `EPT设备履历_${new Date().getTime()}.xlsx`)
  }

</script>

<style lang="less" scoped>
.el-radio {
  margin-right: 9px;
}
</style>
